package com.fresh.controller;

import com.fresh.common.ResponseResult;
import com.github.pagehelper.PageInfo;
import com.fresh.entity.CaiGou;
import com.fresh.entity.CaiGouQO;
import com.fresh.entity.RawIn;
import com.fresh.feignclient.YuanLiaoFeignClient;
import com.fresh.service.CaiGouService;
import com.fresh.util.SnowflakeIdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/caigou")
public class CaiGouController {
    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    CaiGouService caiGouService;
    @Autowired
    YuanLiaoFeignClient yuanLiaoFeignClient;

    @GetMapping({"/list/{pageNum}"})
    public Object list(CaiGouQO caiGouQO, @PathVariable(required = false) Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<CaiGou> pageInfo = caiGouService.findPageInfoByCondition(caiGouQO, pageNum, 4);
        return new ResponseResult(200, "success", pageInfo);

    }

    @PostMapping("/add")
    public Object add(@RequestBody CaiGou caiGou) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);
        String data1 = sdf1.format(dt);

        caiGou.setCgId(snowflakeIdWorker.nextId());
        caiGou.setCgNo("CG" + data);
        caiGou.setCgIn(data1);
        caiGouService.add(caiGou);
        return new ResponseResult(200, "success", null);
    }

    @PostMapping("/update")
    public Object update(@RequestBody CaiGou caiGou) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);

        caiGou.setCgEnd(data);
        caiGouService.update(caiGou);
        return new ResponseResult(200, "success", null);
    }

    //@Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(name = "fsp-create-putIn", rollbackFor = Exception.class)
    @PostMapping("/putIn")
    public Object putIn(@RequestBody RawIn rawIn) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);

        caiGouService.changeStatus3ByCgNo(rawIn.getCgNo(), data);
//        if(true){
//            throw new RuntimeException("模拟异常");
//        }
        return yuanLiaoFeignClient.add(rawIn);
    }

}
